package com.wejoy.video.middle.station.admin.controller.system;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.annotation.RoleCheck;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.screen.ScreenUserCarmeraConfig;
import com.wejoy.video.middle.station.data.domain.system.SysCarmera;
import com.wejoy.video.middle.station.data.domain.system.SysDeptCamera;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.enums.dict.EnumCameraType;
import com.wejoy.video.middle.station.data.enums.dict.EnumVideoCameraMiniType;
import com.wejoy.video.middle.station.data.mapper.screen.IScreenUserCarmeraConfigMapper;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.screen.IScreenUserCarmeraConfigService;
import com.wejoy.video.middle.station.data.service.system.ISysCarmeraService;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.ReturnCode;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system/sysCamera")
public class SysCamerController extends BaseController {
    @Autowired
    private ISysCarmeraService sysCarmeraService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private IScreenUserCarmeraConfigService screenUserCarmeraConfigService;

    /**
     * 保存或更新
     *
     * @param sysCarmera
     * @return RespJSON
     */
    @PostMapping("/save")
    @RoleCheck(name = "point_edit")
    public RespJSON save(@RequestBody SysCarmera sysCarmera, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        sysCarmeraService.save(sysCarmera, loginSysUser.getUserName());
        return RespJSON.success();
    }


    /**
     * 获取本地录像列表
     * @param beginTime
     * @param endTime
     * @param pointId
     * @return
     */
    @GetMapping("/getLocalRecordList")
    private RespJSON getLocalRecordList(String beginTime, String endTime,Integer pointId) {
        JSONObject localRecordList = evsHttpService.getLocalRecordList(evsHttpService.getToken(), pointId, beginTime, endTime);
        return RespJSON.success(localRecordList);
    }

    /**
     * 云台控制
     * @param pointId
     * @return
     */
    @PostMapping("/ptz/{pointId}")
    public RespJSON ptz(@PathVariable Integer pointId,String ptzCommand,Integer speed) {
        return RespJSON.success(evsHttpService.putPtz(evsHttpService.getToken(), pointId, ptzCommand, speed));
    }

    /**
     * 云台控制
     * @param pointId
     * @return
     */
    @PostMapping("/fi/{pointId}")
    public RespJSON fi(@PathVariable Integer pointId,String fiCommand,Integer speed) {
        return RespJSON.success(evsHttpService.fi(evsHttpService.getToken(), pointId, fiCommand, speed));
    }




    /**
     * 分页查询
     *
     * @param sysCarmera
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    @RoleCheck(name = "system:sysDeptCamera:list")
    public RespJSON getPageList(@RequestBody SysCarmera sysCarmera,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.notNull(sysCarmera, "入参对象不能为空");
        WJAssert.notNull(sysCarmera.getDepId(),"部门id不能为空!");
        WJAssert.notNull(sysCarmera.getPageNo(),"分页参数不能为空!");
        WJAssert.notNull(sysCarmera.getPageSize(),"分页参数不能为空!");
        JSONObject points = evsHttpService.getPoints(loginSysUser.getToken(), sysCarmera.getPageSize(), sysCarmera.getPageNo(), sysCarmera.getDepId().intValue(),null,null);
        List<SysCarmera> list = JSONArray.parseArray(points.getString("data"), SysCarmera.class);
        if(CollectionUtils.isEmpty(list)){
            return RespJSON.returnCodeWithMessage(ReturnCode.CUSTOM_MESSAGE, "部门下无设备或参数有误！");
        }
        if (list.size() > 0) {
            list.forEach(item->{
                item.setId(item.getPointId());
                SysCarmera carmera = sysCarmeraService.getOneById(item.getPointId());
                if(!ObjectUtils.isEmpty(carmera)){
                    item.setAlarmsCount(carmera.getAlarmsCount());
                    item.setIsAi(carmera.getIsAi());
                    item.setDepType(carmera.getDepType());
//                    item.setDispatchId(carmera.getDispatchId());
                    JSONArray data = evsHttpService.getPointInfo(evsHttpService.getToken(), item.getPointId()).getJSONArray("data");
                    if(!CollectionUtils.isEmpty(data)){
                        String aiTypes = "";
                        for (int i = 0; i < data.size(); i++) {
                            aiTypes=aiTypes+data.getJSONObject(i).getJSONObject("algorithmAbility").getString("name")+",";
                        }
                        item.setAiTypes(aiTypes);
                    }
                    item.setOnline(item.getPointStatus().equals("ONLINE"));
                    item.setCameraType(carmera.getCameraType());
                    item.setCameraMiniType(carmera.getCameraMiniType());
                    item.setPointStatus(item.getPointStatus().equals("ONLINE")?"在线":"离线");
                    item.setCameraPoiId(carmera.getCameraPoiId());
                    item.setUrls(evsHttpService.pointsSignedUrl(evsHttpService.getToken(), item.getPointId().intValue(),"flv").getJSONArray("urls").toJSONString());
                }
                if(!StringUtils.isEmpty(sysCarmera.getProtocol())){
                    item.setUrls(evsHttpService.pointsSignedUrl( evsHttpService.getToken(), item.getPointId().intValue(),sysCarmera.getProtocol()).toJSONString());;
                }
            });
        }
        PageResult result = new PageResult(sysCarmera.getPageNo(), sysCarmera.getPageSize(), points.getInteger("totalCount"), list);
        return RespJSON.success(result);
    }

    @GetMapping("/pointsSignedUrl/{deviceId}")
    public RespJSON pointsSignedUrl(@PathVariable Integer deviceId){
        return RespJSON.success(evsHttpService.pointsSignedUrl(evsHttpService.getToken(), deviceId,"flv").getJSONArray("urls").toJSONString());
    }

    /**
     * 获取用户记忆的摄像头
     * @return RespJSON
     */
    @GetMapping("/userCameras/{protocol}")
    public RespJSON getPageList(@PathVariable String protocol,Integer type,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        ScreenUserCarmeraConfig carmeraConfig = screenUserCarmeraConfigService.getOneByUserId(loginSysUser.getId(),type);
        if(ObjectUtils.isEmpty(carmeraConfig)){
            return RespJSON.success(null);
        } JSONObject result = new JSONObject();
        if(!StringUtils.isBlank(carmeraConfig.getPointId())){
            String[] split = carmeraConfig.getPointId().split(",");
            JSONArray cameras = new JSONArray();
            for (String s : split) {
                JSONObject pointInfo = evsHttpService.getPointsById(evsHttpService.getToken(), Integer.valueOf(s));
                JSONArray dataArray = pointInfo.getJSONArray("data");
                if(!CollectionUtils.isEmpty(dataArray)){
                    JSONObject data = dataArray.getJSONObject(0);
                    data.put("urls",evsHttpService.pointsSignedUrl(evsHttpService.getToken(), Integer.valueOf(s),protocol));
                    JSONObject pointTagInfoByPointId = evsHttpService.getPointTagInfoByPointId(evsHttpService.getToken(), -1l, Long.valueOf(s), 1, 90);
                    if(!CollectionUtils.isEmpty(pointTagInfoByPointId.getJSONArray("data"))){
                        data.put("tags",pointTagInfoByPointId.getJSONArray("data").getJSONObject(0).getJSONArray("tags"));
                    }
                    cameras.add(data);
                }
            }
            result.put("cameras", cameras);
            result.put("pointIds", carmeraConfig.getPointId());
        }
        return RespJSON.success(result);
    }


    /**
     * 获取算法
     *
     * @param sysCarmera
     * @return RespJSON
     */
    @PostMapping("/getAlgorithm")
    public RespJSON getAlgorithm(@RequestBody SysCarmera sysCarmera) {
        WJAssert.notNull(sysCarmera, "入参对象不能为空");
        WJAssert.notNull(sysCarmera.getPointId(),"点位id不能为空!");
        return RespJSON.success( evsHttpService.getPointInfo(evsHttpService.getToken(), sysCarmera.getPointId()));
    }

    /**
     * 获取算法
     *
     * @param sysCarmera
     * @return RespJSON
     */
    @PostMapping("/getCountBydeptId")
    public RespJSON getCountBydeptId(@RequestBody SysCarmera sysCarmera) {
        WJAssert.notNull(sysCarmera, "入参对象不能为空");
        WJAssert.notNull(sysCarmera.getDepId(),"部门id不能为空!");
        JSONObject result = new JSONObject();
        sysCarmera.setCameraMiniType(EnumVideoCameraMiniType.NORMAL.getCode());
        result.put("NORMAL",sysCarmeraService.getCount(sysCarmera));
        sysCarmera.setCameraMiniType(EnumVideoCameraMiniType.LASER_PTZ.getCode());
        result.put("LASER_PTZ",sysCarmeraService.getCount(sysCarmera));
        sysCarmera.setCameraMiniType(EnumVideoCameraMiniType.PTZ.getCode());
        result.put("PTZ",sysCarmeraService.getCount(sysCarmera));
        sysCarmera.setCameraMiniType(EnumVideoCameraMiniType.MOBILE_CONTROL.getCode());
        result.put("MOBILE_CONTROL",sysCarmeraService.getCount(sysCarmera));
        return RespJSON.success(result);
    }

}
